const fs = require('fs')
const path = require('path')
//导入superagent包，用于node 服务器发送 http请求
const superagent = require('superagent')
//导入cheerio，把superagent请求回来的HTML字符串解析为HTML
const cheerio = require('cheerio')

//获取顶部导航条数据
function getTopBar($) {
  let navTextArr = []
  $('.topbar-nav a').each(function (index, item) {
    let obj = {
      text: $(item).text(),
      href: $(item).attr('href')
    }
    navTextArr.push(obj)
  })
  return navTextArr
}

//获取头部导航条数据
function getHeaderNav($) {
  let navItem = $('.header-nav li.nav-item')
  let arr = []

  navItem.each(function (index, item) {
    let navMenu = []
    $(item).find('.item-children .children-list > li').each(function (i, item) {
      navMenu.push({
        imgUrl: $(item).find('.figure img').attr('src'),
        title: $(item).find('.title').text(),
        price: $(item).find('.price').text()
      })
    })
    arr.push({
      href: $(item).find('a.link').attr('href'),
      text: $(item).find('a.link').text(),
      navMenu: navMenu
    })
  })
  return arr
}

//获取头部产品分类
function getCategory() {
  return new Promise((resolve, reject) => {
    superagent.get('https://list.mi.com').end((err, res) => {
      if (err) return console.log('数据请求失败！请检查网址是否有误')
      let $ = cheerio.load(res.text)
      let arr = []
      let list = $('.container .category-list')
      list.each(function (i, item) {
        let childArr = []
        // console.log($(item).find('.box-bd ul li').html())
        $(item).find('.box-bd ul li').each(function (i, item) {
          let list = []
          list.push({
            imgUrl: $(item).find('.category-list-img img').attr('src'),
            text: $(item).find('.category-list-title').text()
          })
          childArr.push(list)
        })
        arr.push({
          title: $(item).find('.box-hd .title').text(),
          childArr: childArr
        })
      });
      resolve(arr)
    })
  })
}

//获取轮播图
function getCarousel($) {
  let slides = $('#J_homeSlider .slide')
  let arr = []
  slides.each((i, item) => {
    console.log($(item).html())
    arr.push($(item).find('img').attr('src'))
  })
  return arr
}

//获取小米首页所有的数据
function getHomeData() {
  return new Promise((resolve, reject) => {
    superagent.get('https://www.mi.com/')
      .end(async (err, res) => {
        if (err) return console.log('数据请求失败！请检查路径')
        // 把返回值中的页面解析成 HTML
        const $ = cheerio.load(res.text)
        let topBar = getTopBar($) //获取顶部导航条
        let headerBar = getHeaderNav($)//获取头部导航
        let category = await getCategory()//获取侧边分类
        let carousel = getCarousel($)//获取焦点轮播图
        // console.log($('div').text())
        let arr = {
          status: 200,
          code: 0,
          data: {
            topBar,
            headerBar,
            category,
            carousel
          }
        }
        console.log(arr)
        fs.writeFile(path.join(__dirname,'home.json'),JSON.stringify(arr),function (err) {
          if (err){
            console.log('文件写入失败！')
          } else {}
          console.log('文件写入成功！')
        })
        resolve(arr)
      })
  })
}

module.exports = {
  getHomeData
}
